package com.woniuxy.student.controller;

import com.woniuxy.commons.entity.ResponseResult;
import com.woniuxy.commons.entity.wyh.DivideClasses;
import com.woniuxy.commons.entity.wyh.MessageRecord;
import com.woniuxy.commons.enums.MessageTypeEnum;
import com.woniuxy.commons.utils.TimeUtil;
import com.woniuxy.student.service.MessageRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;

import static com.woniuxy.commons.enums.TermEnum.HIGH_TWO_FIRST;

@RestController
@RequestMapping("divide")
public class DivideController {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private MessageRecordService messageRecordService;

    @RequestMapping("/id/{value}/{beginTime}/{endTime}")
    public ResponseResult getDivideDate(@PathVariable("value") String value,@PathVariable("beginTime") String beginTime,@PathVariable("endTime") String endTime) throws ParseException {
        System.out.println(value+":"+beginTime+endTime);
        //获取高二上的id
        Long index = HIGH_TWO_FIRST.getIndex();
        //获取最后的时间判断是否过期及学生年级id=3
        //通过学生id查询年级id是否为3
        //伪数据 studentID = 1 ； 年级id = 3
        if(index == 3 && TimeUtil.getTimeFile(endTime) > System.currentTimeMillis()){
            //key学生id加消息时间为key，存入消息时间---
            MessageRecord messageRecord = new MessageRecord().setBeginTime(beginTime).setUid(1).setTime(TimeUtil.getTimeString(new Date().getTime())).setSubject(value);
            int judge = messageRecordService.findMessageRecord(messageRecord);
            if(judge != -1 ) {
                redisTemplate.opsForValue().set("1",beginTime);
            }else {
                return new ResponseResult().setMessage("系统匆忙，请重试").setCode(500);
            }
            return new ResponseResult().setMessage("你已经选择"+value+"报名成功!").setCode(200);
        }
        return new ResponseResult().setMessage("已过期...请联系管理人员").setCode(500);
    }

    @RequestMapping("/sid/{id}")
    public ResponseResult scan(@PathVariable("id") Integer id){
        //id是虚拟的id，通过用户获取对应年级的学生id
        DivideClasses divideClasses = (DivideClasses)redisTemplate.opsForValue().get(MessageTypeEnum.DIVIDE.getName());
        System.out.println(divideClasses);
        if (redisTemplate.opsForValue().get(MessageTypeEnum.DIVIDE.getName()) != null && redisTemplate.opsForValue().get("1") == null){
            return new ResponseResult().setCode(400).setMessage("已有消息未处理").setData(divideClasses.getBeginTime()+","+divideClasses.getEndTime()+","+divideClasses.getTeamType());
        }
        return new ResponseResult().setCode(200).setMessage("已处理消息");
    }
}
